<template>
  <el-container style="height: 100%; display: flex; flex-direction: column;">
    <el-header style="display: flex; justify-content: space-between; align-items: center;">
      <el-dropdown @command="handleFilter">
        <el-button type="primary" style="width:10vw;">
          {{ Filter }}<i class="el-icon-arrow-down el-icon--right"></i>
        </el-button>
        <el-dropdown-menu slot="dropdown" style="text-align: center;">
          <el-dropdown-item command="全部">全部</el-dropdown-item>
          <el-dropdown-item v-for="(item, index) in tableTitle" :command="item.label">{{ item.label }}</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>

      <el-input v-model="search" placeholder="请输入内容" clearable="true" style="width: 20vw;"></el-input>
      <el-button @click="handleSearch" :disabled="search ? false : true">搜索</el-button>
      <el-button @click="handleReset">重置</el-button>
      <el-button @click="handleRefresh">刷新</el-button>
      <el-button @click="addnew">新建</el-button>
    </el-header>
    <el-main style="flex: 1; overflow-y: auto;">
      <el-table :data="paginatedData" style="width:100%" v-loading="loading">
        <el-table-column v-for="(item, index) in tableTitle" align="center" :key="index" :prop="item.tableProp" :label="item.label" :formatter="formatFlag" :width="item.width"></el-table-column>

        <el-table-column align="center" label="操作" width="100">
          <template slot-scope="scope">
            <el-button @click="handleDetails(scope.row)" type="text" size="small">详情</el-button>
            <el-button @click="handleDelete(scope.row)" type="text" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-main>
    <el-dialog v-bind:title="dialogTitle" :visible.sync="dialogFormVisible">
      <el-form ref="form" :rules="rules" :model="form" @submit.native.prevent>
        <el-form-item prop="address" label="大门位置" :label-width="formLabelWidth">
          <el-input v-model="form.address" autocomplete="off" :readonly="!isEditable"></el-input>
        </el-form-item>
        <el-form-item prop="status" label="大门状态" :label-width="formLabelWidth">
          <el-select v-model="form.status" placeholder="请选择" :disabled="!isEditable">
            <el-option label="可用" value="可用"></el-option>
            <el-option label="不可用" value="不可用"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="type" label="大门类型" :label-width="formLabelWidth">
          <el-input v-model="form.type" autocomplete="off" readonly></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <div v-if="isCreateMode === false">
          <el-button type="warning" @click="toggleEdit">编 辑</el-button>
          <el-button type="primary" @click="confirm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
        <div v-if="isCreateMode">
          <el-button type="primary" @click="confirmAdd">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </div>
    </el-dialog>

    <el-footer style="text-align: center;">
      <el-pagination
          layout="total, prev, pager, next"
          :total="tableData.length"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handlePageChange">
      </el-pagination>
    </el-footer>
  </el-container>
</template>
<script>
import http from '@/utils/http';
import {assertSourceType} from "@babel/core/lib/config/validation/option-assertions";
import {config} from "@vue/cli-plugin-eslint/eslintOptions";

export default {
  data() {
    return {
      loading: false,
      filteredList: [],
      Filter: '全部',
      search: "",
      currentPage: 1,
      pageSize: 10,
      allInfo: [],
      tableTitle: [
        //0为大门门禁，1为停车场门禁
        { tableProp: "id", label: "大门门禁ID" },
        { tableProp: "address", label: "大门门禁位置" },
        { tableProp: "status", label: "大门门禁状态" },
        { tableProp: "type", label: "大门门禁类型" }
      ],
      tableData: [],
      dialogFormVisible: false,
      isCreateMode: false,
      form: {
        id: '',
        address: '',
        status: '',
        type: '大门门禁'
      },
      originalForm: null,
      isEditable: false,
      dialogTitle: '',
      formLabelWidth: '120px',
      rules: {
        address: [
          { required: true, message: '大门门禁位置不能为空', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '大门门禁状态不能为空', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '大门门禁类型不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    paginatedData() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = this.currentPage * this.pageSize;
      return this.tableData.slice(start, end);
    }
  },
  mounted() {
    this.getAllData();
  },
  methods: {
    handleRefresh() {
      this.getAllData();
    },
    formatFlag(row,column,cellValue){
      // row: 当前行数据对象
      // column: 当前列的配置对象
      // cellValue: 当前单元格的值，即 row[column.property]
      // { tableProp: "id", label: "大门门禁ID" },
      // { tableProp: "address", label: "大门门禁位置" },
      // { tableProp: "status", label: "大门门禁状态" },
      // { tableProp: "type", label: "大门门禁类型" }

      const statusMap = {
        0: '不可用',
        1: '可用'
      };
      const typeMap = {
        0: '大门门禁',
        1: '停车场门禁',
      };
      if (column.property === 'status') {
        return statusMap[cellValue] || '未知状态';
      }
      if (column.property === 'type') {
        return typeMap[cellValue] || '未知类型';
      }
      return cellValue;
    },
    getAllData() {
      this.loading = true;
      http.get("/admin/door/getAllDoor")
          .then((response) => {
            const Result = response.data;
            //this.tableData = this.allInfo.filter(item => item.type === 1);
            this.allInfo = Result.data.filter(item => item.type === 0 );
            this.tableData = this.allInfo;
            this.loading = false;
          }).catch(function (error) {
        console.error(error);
      });
    },
    resetForm() {
      this.$nextTick(() => {
        this.form = {
          id: '',
          address: '',
          status: '',
          type: '大门门禁'
        };
        this.$refs.form.resetFields();
      });
    },
    addnew() {
      this.resetForm();
      this.dialogFormVisible = true;
      this.isEditable = true;
      this.isCreateMode = true;
      this.dialogTitle = '新建门禁信息';
    },
    handleReset() {
      this.search = "";
      this.Filter = "全部";
      this.tableData = this.allInfo;
    },
    handleFilter(command) {
      this.Filter = command;
    },
    handleSearch() {
      if (this.search) {
        if (this.Filter === "全部") {
          this.tableData = this.allInfo.filter(item => {
            return Object.keys(item).some(key => {
              return this.tableTitle.some(title => title.tableProp === key) &&
                  item[key] && item[key].toString().toLowerCase().includes(this.search.toLowerCase());
            });
          });
        } else {
          const nowtable = this.tableTitle.find(item => item.label === this.Filter).tableProp;
          this.tableData = this.allInfo.filter(item => {
            const value = item[nowtable] ? item[nowtable].toString().toLowerCase() : '';
            return value.includes(this.search.toLowerCase());
          });
        }
      }
    },
    handleDetails(row) {
      this.resetForm();
      setTimeout(()=>{
          this.form = { ...row };
          this.form.status = (row.status == '1' ? '可用' : '不可用');
          this.form.type = (row.type == '1' ? '停车场门禁' : '大门门禁');
          this.originalForm = { ...this.form };
          this.dialogFormVisible = true;
          this.isEditable = false;
          this.isCreateMode = false;
          this.dialogTitle = '大门门禁信息详情|信息编辑';
      },100);

    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除条目, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
        this.deleteData(row);
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    deleteData(row) {
      this.tableData = this.tableData.filter(item => item != row);
      this.allInfo = this.tableData;

      const totalPages = Math.ceil(this.allInfo.length / this.pageSize);
      if (this.currentPage > totalPages) {
        this.currentPage -= 1;
      }

      http.get("/admin/door/deleteDoor", {
        params: {
          id: row.id
        }
      }).then(response => {
        console.log(response.data.data);
      })
    },
    handlePageChange(page) {
      this.currentPage = page;
    },
    toggleEdit() {
      this.$message.warning("正在进行编辑");
      this.isEditable = true;
    },
    cancel() {
      if (this.isCreateMode === false) {
        this.form = {...this.originalForm};
      }
      this.dialogFormVisible = false;
      this.isEditable = false;
    },
    confirmAdd() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          //console.log(this.form);
          http.get("/admin/door/addDoor", {
            params: {
              address: this.form.address,
              status: (this.form.status === '可用' ? '1' : '0'),
              type: (this.form.type === '大门门禁' ? '0' : '1')
            }
          })
              .then(response => {
                const Result = response.data;
                console.log(response);
                if (Result.success) {
                  this.getAllData();
                  this.$message.success("添加成功！");
                  this.dialogFormVisible = false;
                  this.isEditable = false;
                } else {
                  this.$message.error(Result.errorMsg);
                }
              })
              .catch(error => {
                console.error(error);
                this.$message.error("请求失败！");
              });
        } else {
          this.$message.error('数据格式有误，请重新输入！');
          return false;
        }
      });
    },
    confirm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          http.post('/admin/door/updateDoor', {
            id: this.form.id,
            address: this.form.address,
            status: (this.form.status == '可用' ? '1' : '0'),
            type: (this.form.type == '大门门禁' ? '0' : '1')
          })
              .then(response => {
                const Result = response.data;
                if (Result.success) {
                  this.getAllData();
                  this.$message.success("修改成功！");
                  this.dialogFormVisible = false;
                  this.isEditable = false;
                } else {
                  this.$message.error(Result.errorMsg);
                }
              })
              .catch(error => {
                console.error(error);
                this.$message.error("请求失败！");
              });
        } else {
          this.$message.error('数据格式有误，请重新输入！');
          this.form = {...this.originalForm};
        }
      });
    }
  }
}
</script>

<style scoped lang="scss">
</style>